package com.scriptback.service.Impl;

import com.scriptback.entity.Project;
import com.scriptback.repository.ProjectRepository;
import com.scriptback.service.ProjectService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 项目服务实现类
 */
@Service
@Transactional
public class ProjectServiceImpl implements ProjectService {

    @Autowired
    private ProjectRepository projectRepository;

    /**
     * 创建新项目
     */
    @Override
    public Project createProject(String name, String description) {
        Project project = new Project(name,description);
        return projectRepository.save(project);
    }

    /**
     * 分页获取所有项目
     */
    @Override
    public Page<Project> getAllProjects(Pageable pageable) {
        return projectRepository.findAllByOrderByIdDesc(pageable);
    }

    /**
     * 按名称搜索项目
     */
    @Override
    public Page<Project> searchProjectsByName(String name, Pageable pageable) {
        return projectRepository.findByNameContainingIgnoreCase(name,pageable);
    }

    /**
     * 根据ID获取项目
     */
    @Override
    public Project getProjectById(String id) {
        return projectRepository.findById(id).orElseThrow(() -> new RuntimeException("项目不存在"));
    }

    /**
     * 更新项目信息
     */
    @Override
    public Project updateProject(String id, String name, String description) {
        Project projectById = getProjectById(id);
        projectById.setName(name);
        projectById.setDescription(description);
        return projectRepository.save(projectById);
    }

    /**
     * 删除项目
     */
    @Override
    public void deleteProject(String id) {
        projectRepository.deleteById(id);
    }
}
